package com.beiji.lib.pen.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Rect
import com.beiji.lib.pen.PenLog
import java.io.File


/**
 * Png裁剪辅助类
 * Created by X on 2018/7/28.
 */
object PngCropHelper {

    /**
     * 裁剪png图片空白部分
     */
    fun cropPng(srcFilePath: String, targetFile: File) {
        val newOptions = BitmapFactory.Options()
        newOptions.inMutable = true
        val bitmap = BitmapFactory.decodeFile(srcFilePath, newOptions)
        cropPng(bitmap, targetFile)
    }

    /**
     * 裁剪png图片空白部分
     */
    fun cropPng(bitmap: Bitmap?, targetFile: File) {
        bitmap ?: return
        val width = bitmap.width
        val height = bitmap.height
        //创建像素点数组
        val pixels = IntArray(width * height)
        var grey: Int
//        val rect = Rect(width, height, 0, 0)
        //横向不裁剪
        val rect = Rect(0, height, width, 0)
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
        for (i in 0 until height) {
            for (j in 0 until width) {
                grey = pixels[width * i + j]
                if (grey != 0) {
                    //检测左右边距
                    if (rect.left > j) {
                        rect.left = j
                    }
                    if (rect.right < j) {
                        rect.right = j
                    }
                    //检测上下边距
                    if (rect.top > i) {
                        rect.top = i
                    }
                    if (rect.bottom < i) {
                        rect.bottom = i
                    }
                }
            }
        }
        val newWidth = rect.right - rect.left + 1
        var newHeight = rect.bottom - rect.top + 1
        if(newHeight < 0){
            newHeight = 1
        }
        if (newHeight < 0 || newWidth < 0){
            return
        }
        //有效像素点数组
        val validPixels = IntArray(newWidth * newHeight)
        for (i in rect.top until rect.bottom) {
            val row = i - rect.top
            for (j in rect.left until rect.right) {
                val column = j - rect.left
//                AWLog.e("bitmap", (newWidth * row + column).toString() + " -> " + (width * i + j).toString())
                validPixels[newWidth * row + column] = pixels[width * i + j]
            }
        }
        PenLog.i("bitmap", "width->$width,height->$height")
        PenLog.i("bitmap", "valid rect -> $rect")
        val croppedBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888)
        croppedBitmap.setPixels(validPixels, 0, newWidth, 0, 0, newWidth, newHeight)
        if (targetFile.exists()) {
            targetFile.delete()
        }
        val outputStream = targetFile.outputStream()
        croppedBitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream)
        outputStream.close()
    }

}